package com.cola.colaboot.module.system.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.cola.colaboot.config.dto.Res;
import com.cola.colaboot.config.exception.ColaException;
import com.cola.colaboot.utils.FileUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/file")
public class SysFileController {

    public static final String FILE_ROOT_URL = "/opt/upload/file/";
    public static Map<String,Integer> fileSizeLimit = new HashMap<>();//文件夹上传大小限制，
    static {
        fileSizeLimit.put("imgPool",10);
    }


    /**
     *  文件上传
     * @param dir   文件夹名
     */
    @PostMapping("/upload")
    public Res<?> upload(@RequestParam("file") MultipartFile multipartFile,
                         @RequestParam("dir") String dir, @RequestParam(value = "fileName",required = false) String fileName){
        if(StringUtils.isBlank(dir)){
            throw new ColaException("文件夹名不能为空");
        }
        Integer sizeLimit = fileSizeLimit.get(dir);
        if (multipartFile.getSize() > Objects.requireNonNullElse(sizeLimit, 10) * 1024 * 1024) {
            throw new ColaException("文件过大");
        }
        File file = FileUtil.saveFile(FILE_ROOT_URL + dir, fileName, multipartFile);
        return Res.ok("success","/"+dir+"/"+file.getName());
    }

}
